import { Component, Input, Output, EventEmitter, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { RepairWorkflowService } from '../../services/repair-workflow.service';
import { 
  WorkflowInstance, 
  ExternalVendor, 
  WorkflowActionResponse,
  RepairPriority 
} from '../../models/repair-workflow.model';

@Component({
  selector: 'app-workflow-step',
  templateUrl: './workflow-step.component.html',
  styleUrls: ['./workflow-step.component.scss']
})
export class WorkflowStepComponent implements OnInit {
  @Input() workflowInstance!: WorkflowInstance;
  @Output() stepCompleted = new EventEmitter<void>();

  stepForm!: FormGroup;
  externalVendors: ExternalVendor[] = [];
  loading = false;
  error: string | null = null;

  constructor(
    private fb: FormBuilder,
    private workflowService: RepairWorkflowService
  ) {}

  ngOnInit(): void {
    this.initializeForm();
    this.loadExternalVendors();
  }

  private initializeForm(): void {
    switch (this.workflowInstance.currentStep) {
      case 'DecisionPending':
        this.stepForm = this.fb.group({
          isExternalRepair: [null, Validators.required],
          reason: ['', Validators.required]
        });
        break;

      case 'ExternalVendorForm':
        this.stepForm = this.fb.group({
          externalVendorId: [null, Validators.required]
        });
        break;

      case 'InternalRepairForm':
        this.stepForm = this.fb.group({
          repairPlan: ['', Validators.required],
          estimatedHours: [null, [Validators.required, Validators.min(1)]],
          notes: ['']
        });
        break;

      case 'RepairDetailsForm':
        this.stepForm = this.fb.group({
          repairContent: ['', Validators.required],
          repairHours: [null, [Validators.required, Validators.min(1)]],
          repairCost: [null, [Validators.required, Validators.min(0)]],
          repairNotes: ['']
        });
        break;

      case 'ApprovalPending':
        this.stepForm = this.fb.group({
          isApproved: [null, Validators.required],
          approvalNotes: ['']
        });
        break;

      default:
        this.stepForm = this.fb.group({});
    }
  }

  private loadExternalVendors(): void {
    if (this.workflowInstance.currentStep === 'ExternalVendorForm') {
      this.workflowService.getExternalVendors().subscribe(vendors => {
        this.externalVendors = vendors;
      });
    }
  }

  onSubmit(): void {
    if (this.stepForm.invalid) {
      this.markFormGroupTouched();
      return;
    }

    this.loading = true;
    this.error = null;

    const formValue = this.stepForm.value;

    switch (this.workflowInstance.currentStep) {
      case 'DecisionPending':
        this.makeDecision(formValue.isExternalRepair);
        break;

      case 'ExternalVendorForm':
        this.submitExternalVendor(formValue.externalVendorId);
        break;

      case 'InternalRepairForm':
        this.submitInternalRepair();
        break;

      case 'RepairDetailsForm':
        this.submitRepairDetails(
          formValue.repairContent,
          formValue.repairHours,
          formValue.repairCost,
          formValue.repairNotes
        );
        break;

      case 'ApprovalPending':
        this.submitApproval(formValue.isApproved, formValue.approvalNotes);
        break;

      default:
        this.loading = false;
        this.error = 'Unknown workflow step';
    }
  }

  private makeDecision(isExternalRepair: boolean): void {
    this.workflowService.makeDecision(this.workflowInstance.id, isExternalRepair)
      .subscribe(
        (response: WorkflowActionResponse) => {
          this.handleResponse(response);
        },
        error => this.handleError(error)
      );
  }

  private submitExternalVendor(externalVendorId: number): void {
    this.workflowService.submitExternalVendor(this.workflowInstance.id, externalVendorId)
      .subscribe(
        (response: WorkflowActionResponse) => {
          this.handleResponse(response);
        },
        error => this.handleError(error)
      );
  }

  private submitInternalRepair(): void {
    this.workflowService.submitInternalRepair(this.workflowInstance.id)
      .subscribe(
        (response: WorkflowActionResponse) => {
          this.handleResponse(response);
        },
        error => this.handleError(error)
      );
  }

  private submitRepairDetails(repairContent: string, repairHours: number, repairCost: number, repairNotes?: string): void {
    this.workflowService.submitRepairDetails(
      this.workflowInstance.id,
      repairContent,
      repairHours,
      repairCost,
      repairNotes
    ).subscribe(
      (response: WorkflowActionResponse) => {
        this.handleResponse(response);
      },
      error => this.handleError(error)
    );
  }

  private submitApproval(isApproved: boolean, approvalNotes?: string): void {
    this.workflowService.submitApproval(this.workflowInstance.id, isApproved, approvalNotes)
      .subscribe(
        (response: WorkflowActionResponse) => {
          this.handleResponse(response);
        },
        error => this.handleError(error)
      );
  }

  private handleResponse(response: WorkflowActionResponse): void {
    this.loading = false;
    if (response && response.success) {
      this.stepCompleted.emit();
    } else {
      this.error = response?.message || 'Unknown error occurred';
    }
  }

  private handleError(error: any): void {
    this.loading = false;
    this.error = error.message || 'An error occurred while processing the request';
    console.error('Workflow step error:', error);
  }

  private markFormGroupTouched(): void {
    Object.keys(this.stepForm.controls).forEach(key => {
      const control = this.stepForm.get(key);
      control?.markAsTouched();
    });
  }

  // Helper methods for template
  isFieldInvalid(fieldName: string): boolean {
    const field = this.stepForm.get(fieldName);
    return !!(field && field.invalid && field.touched);
  }

  getFieldError(fieldName: string): string {
    const field = this.stepForm.get(fieldName);
    if (field && field.errors && field.touched) {
      if (field.errors['required']) {
        return '此字段为必填项';
      }
      if (field.errors['min']) {
        return `最小值为 ${field.errors['min'].min}`;
      }
    }
    return '';
  }

  getStepTitle(): string {
    return this.workflowService.getWorkflowStepText(this.workflowInstance.currentStep);
  }

  getRepairPriorityText(): string {
    return this.workflowService.getRepairPriorityText(this.workflowInstance.repairRequest.priority);
  }
} 